home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2002 November / SGI IRIX Base Documentation 2002 November.iso / usr / share / catman / u_man / cat1 / perltoot.z / perltoot
Encoding:
Text File  |  2002-10-03  |  90.2 KB  |  2,377 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perltoot - Tom's object-oriented tutorial for perl
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      Object-oriented programming is a big seller these days.  Some managers
  13.      would rather have objects than sliced bread.  Why is that?  What's so
  14.      special about an object?  Just what _i_s an object anyway?
  15.  
  16.      An object is nothing but a way of tucking away complex behaviours into a
  17.      neat little easy-to-use bundle.  (This is what professors call
  18.      abstraction.) Smart people who have nothing to do but sit around for
  19.      weeks on end figuring out really hard problems make these nifty objects
  20.      that even regular people can use. (This is what professors call software
  21.      reuse.)  Users (well, programmers) can play with this little bundle all
  22.      they want, but they aren't to open it up and mess with the insides.  Just
  23.      like an expensive piece of hardware, the contract says that you void the
  24.      warranty if you muck with the cover.  So don't do that.
  25.  
  26.      The heart of objects is the class, a protected little private namespace
  27.      full of data and functions.  A class is a set of related routines that
  28.      addresses some problem area.  You can think of it as a user-defined type.
  29.      The Perl package mechanism, also used for more traditional modules, is
  30.      used for class modules as well.  Objects "live" in a class, meaning that
  31.      they belong to some package.
  32.  
  33.      More often than not, the class provides the user with little bundles.
  34.      These bundles are objects.  They know whose class they belong to, and how
  35.      to behave.  Users ask the class to do something, like "give me an
  36.      object."  Or they can ask one of these objects to do something.  Asking a
  37.      class to do something for you is calling a _c_l_a_s_s _m_e_t_h_o_d.  Asking an
  38.      object to do something for you is calling an _o_b_j_e_c_t _m_e_t_h_o_d.  Asking
  39.      either a class (usually) or an object (sometimes) to give you back an
  40.      object is calling a _c_o_n_s_t_r_u_c_t_o_r, which is just a kind of method.
  41.  
  42.      That's all well and good, but how is an object different from any other
  43.      Perl data type?  Just what is an object _r_e_a_l_l_y; that is, what's its
  44.      fundamental type?  The answer to the first question is easy.  An object
  45.      is different from any other data type in Perl in one and only one way:
  46.      you may dereference it using not merely string or numeric subscripts as
  47.      with simple arrays and hashes, but with named subroutine calls.  In a
  48.      word, with _m_e_t_h_o_d_s.
  49.  
  50.      The answer to the second question is that it's a reference, and not just
  51.      any reference, mind you, but one whose referent has been _b_l_e_s_s()ed into a
  52.      particular class (read: package).  What kind of reference?  Well, the
  53.      answer to that one is a bit less concrete.  That's because in Perl the
  54.      designer of the class can employ any sort of reference they'd like as the
  55.      underlying intrinsic data type.  It could be a scalar, an array, or a
  56.      hash reference.  It could even be a code reference.  But because of its
  57.      inherent flexibility, an object is usually a hash reference.
  58.  
  59.  
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  71.  
  72.  
  73.  
  74. CCCCrrrreeeeaaaattttiiiinnnngggg aaaa CCCCllllaaaassssssss
  75.      Before you create a class, you need to decide what to name it.  That's
  76.      because the class (package) name governs the name of the file used to
  77.      house it, just as with regular modules.  Then, that class (package)
  78.      should provide one or more ways to generate objects.  Finally, it should
  79.      provide mechanisms to allow users of its objects to indirectly manipulate
  80.      these objects from a distance.
  81.  
  82.      For example, let's make a simple Person class module.  It gets stored in
  83.      the file Person.pm.  If it were called a Happy::Person class, it would be
  84.      stored in the file Happy/Person.pm, and its package would become
  85.      Happy::Person instead of just Person.  (On a personal computer not
  86.      running Unix or Plan 9, but something like MacOS or VMS, the directory
  87.      separator may be different, but the principle is the same.)  Do not
  88.      assume any formal relationship between modules based on their directory
  89.      names.  This is merely a grouping convenience, and has no effect on
  90.      inheritance, variable accessibility, or anything else.
  91.  
  92.      For this module we aren't going to use Exporter, because we're a well-
  93.      behaved class module that doesn't export anything at all.  In order to
  94.      manufacture objects, a class needs to have a _c_o_n_s_t_r_u_c_t_o_r _m_e_t_h_o_d.  A
  95.      constructor gives you back not just a regular data type, but a brand-new
  96.      object in that class.  This magic is taken care of by the _b_l_e_s_s()
  97.      function, whose sole purpose is to enable its referent to be used as an
  98.      object.  Remember: being an object really means nothing more than that
  99.      methods may now be called against it.
  100.  
  101.      While a constructor may be named anything you'd like, most Perl
  102.      programmers seem to like to call theirs _n_e_w().  However, _n_e_w() is not a
  103.      reserved word, and a class is under no obligation to supply such.  Some
  104.      programmers have also been known to use a function with the same name as
  105.      the class as the constructor.
  106.  
  107.      OOOObbbbjjjjeeeecccctttt RRRReeeepppprrrreeeesssseeeennnnttttaaaattttiiiioooonnnn
  108.  
  109.      By far the most common mechanism used in Perl to represent a Pascal
  110.      record, a C struct, or a C++ class is an anonymous hash.  That's because
  111.      a hash has an arbitrary number of data fields, each conveniently accessed
  112.      by an arbitrary name of your own devising.
  113.  
  114.      If you were just doing a simple struct-like emulation, you would likely
  115.      go about it something like this:
  116.  
  117.          $rec = {
  118.              name  => "Jason",
  119.              age   => 23,
  120.              peers => [ "Norbert", "Rhys", "Phineas"],
  121.          };
  122.  
  123.      If you felt like it, you could add a bit of visual distinction by up-
  124.      casing the hash keys:
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  137.  
  138.  
  139.  
  140.          $rec = {
  141.              NAME  => "Jason",
  142.              AGE   => 23,
  143.              PEERS => [ "Norbert", "Rhys", "Phineas"],
  144.          };
  145.  
  146.      And so you could get at $rec->{NAME} to find "Jason", or @{ $rec->{PEERS}
  147.      } to get at "Norbert", "Rhys", and "Phineas".  (Have you ever noticed how
  148.      many 23-year-old programmers seem to be named "Jason" these days? :-)
  149.  
  150.      This same model is often used for classes, although it is not considered
  151.      the pinnacle of programming propriety for folks from outside the class to
  152.      come waltzing into an object, brazenly accessing its data members
  153.      directly.  Generally speaking, an object should be considered an opaque
  154.      cookie that you use _o_b_j_e_c_t _m_e_t_h_o_d_s to access.  Visually, methods look
  155.      like you're dereffing a reference using a function name instead of
  156.      brackets or braces.
  157.  
  158.      CCCCllllaaaassssssss IIIInnnntttteeeerrrrffffaaaacccceeee
  159.  
  160.      Some languages provide a formal syntactic interface to a class's methods,
  161.      but Perl does not.  It relies on you to read the documentation of each
  162.      class.  If you try to call an undefined method on an object, Perl won't
  163.      complain, but the program will trigger an exception while it's running.
  164.      Likewise, if you call a method expecting a prime number as its argument
  165.      with a non-prime one instead, you can't expect the compiler to catch
  166.      this.  (Well, you can expect it all you like, but it's not going to
  167.      happen.)
  168.  
  169.      Let's suppose you have a well-educated user of your Person class, someone
  170.      who has read the docs that explain the prescribed interface.  Here's how
  171.      they might use the Person class:
  172.  
  173.          use Person;
  174.  
  175.          $him = Person->new();
  176.          $him->name("Jason");
  177.          $him->age(23);
  178.          $him->peers( "Norbert", "Rhys", "Phineas" );
  179.  
  180.          push @All_Recs, $him;  # save object in array for later
  181.  
  182.          printf "%s is %d years old.\n", $him->name, $him->age;
  183.          print "His peers are: ", join(", ", $him->peers), "\n";
  184.  
  185.          printf "Last rec's name is %s\n", $All_Recs[-1]->name;
  186.  
  187.      As you can see, the user of the class doesn't know (or at least, has no
  188.      business paying attention to the fact) that the object has one particular
  189.      implementation or another.  The interface to the class and its objects is
  190.      exclusively via methods, and that's all the user of the class should ever
  191.      play with.
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  203.  
  204.  
  205.  
  206.      CCCCoooonnnnssssttttrrrruuuuccccttttoooorrrrssss aaaannnndddd IIIInnnnssssttttaaaannnncccceeee MMMMeeeetttthhhhooooddddssss
  207.  
  208.      Still, _s_o_m_e_o_n_e has to know what's in the object.  And that someone is the
  209.      class.  It implements methods that the programmer uses to access the
  210.      object.  Here's how to implement the Person class using the standard
  211.      hash-ref-as-an-object idiom.  We'll make a class method called _n_e_w() to
  212.      act as the constructor, and three object methods called _n_a_m_e(), _a_g_e(),
  213.      and _p_e_e_r_s() to get at per-object data hidden away in our anonymous hash.
  214.  
  215.          package Person;
  216.          use strict;
  217.  
  218.          ##################################################
  219.          ## the object constructor (simplistic version)  ##
  220.          ##################################################
  221.          sub new {
  222.              my $self  = {};
  223.              $self->{NAME}   = undef;
  224.              $self->{AGE}    = undef;
  225.              $self->{PEERS}  = [];
  226.              bless($self);           # but see below
  227.              return $self;
  228.          }
  229.  
  230.          ##############################################
  231.          ## methods to access per-object data        ##
  232.          ##                                          ##
  233.          ## With args, they set the value.  Without  ##
  234.          ## any, they only retrieve it/them.         ##
  235.          ##############################################
  236.  
  237.          sub name {
  238.              my $self = shift;
  239.              if (@_) { $self->{NAME} = shift }
  240.              return $self->{NAME};
  241.          }
  242.  
  243.          sub age {
  244.              my $self = shift;
  245.              if (@_) { $self->{AGE} = shift }
  246.              return $self->{AGE};
  247.          }
  248.  
  249.          sub peers {
  250.              my $self = shift;
  251.              if (@_) { @{ $self->{PEERS} } = @_ }
  252.              return @{ $self->{PEERS} };
  253.          }
  254.  
  255.          1;  # so the require or use succeeds
  256.  
  257.      We've created three methods to access an object's data, _n_a_m_e(), _a_g_e(),
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  269.  
  270.  
  271.  
  272.      and _p_e_e_r_s().  These are all substantially similar.  If called with an
  273.      argument, they set the appropriate field; otherwise they return the value
  274.      held by that field, meaning the value of that hash key.
  275.  
  276.      PPPPllllaaaannnnnnnniiiinnnngggg ffffoooorrrr tttthhhheeee FFFFuuuuttttuuuurrrreeee:::: BBBBeeeetttttttteeeerrrr CCCCoooonnnnssssttttrrrruuuuccccttttoooorrrrssss
  277.  
  278.      Even though at this point you may not even know what it means, someday
  279.      you're going to worry about inheritance.  (You can safely ignore this for
  280.      now and worry about it later if you'd like.)  To ensure that this all
  281.      works out smoothly, you must use the double-argument form of _b_l_e_s_s().
  282.      The second argument is the class into which the referent will be blessed.
  283.      By not assuming our own class as the default second argument and instead
  284.      using the class passed into us, we make our constructor inheritable.
  285.  
  286.      While we're at it, let's make our constructor a bit more flexible.
  287.      Rather than being uniquely a class method, we'll set it up so that it can
  288.      be called as either a class method _o_r an object method.  That way you can
  289.      say:
  290.  
  291.          $me  = Person->new();
  292.          $him = $me->new();
  293.  
  294.      To do this, all we have to do is check whether what was passed in was a
  295.      reference or not.  If so, we were invoked as an object method, and we
  296.      need to extract the package (class) using the _r_e_f() function.  If not, we
  297.      just use the string passed in as the package name for blessing our
  298.      referent.
  299.  
  300.          sub new {
  301.              my $proto = shift;
  302.              my $class = ref($proto) || $proto;
  303.              my $self  = {};
  304.              $self->{NAME}   = undef;
  305.              $self->{AGE}    = undef;
  306.              $self->{PEERS}  = [];
  307.              bless ($self, $class);
  308.              return $self;
  309.          }
  310.  
  311.      That's about all there is for constructors.  These methods bring objects
  312.      to life, returning neat little opaque bundles to the user to be used in
  313.      subsequent method calls.
  314.  
  315.      DDDDeeeessssttttrrrruuuuccccttttoooorrrrssss
  316.  
  317.      Every story has a beginning and an end.  The beginning of the object's
  318.      story is its constructor, explicitly called when the object comes into
  319.      existence.  But the ending of its story is the _d_e_s_t_r_u_c_t_o_r, a method
  320.      implicitly called when an object leaves this life.  Any per-object
  321.      clean-up code is placed in the destructor, which must (in Perl) be called
  322.      DESTROY.
  323.  
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  335.  
  336.  
  337.  
  338.      If constructors can have arbitrary names, then why not destructors?
  339.      Because while a constructor is explicitly called, a destructor is not.
  340.      Destruction happens automatically via Perl's garbage collection (GC)
  341.      system, which is a quick but somewhat lazy reference-based GC system.  To
  342.      know what to call, Perl insists that the destructor be named DESTROY.
  343.      Perl's notion of the right time to call a destructor is not well-defined
  344.      currently, which is why your destructors should not rely on when they are
  345.      called.
  346.  
  347.      Why is DESTROY in all caps?  Perl on occasion uses purely uppercase
  348.      function names as a convention to indicate that the function will be
  349.      automatically called by Perl in some way.  Others that are called
  350.      implicitly include BEGIN, END, AUTOLOAD, plus all methods used by tied
  351.      objects, described in the _p_e_r_l_t_i_e manpage.
  352.  
  353.      In really good object-oriented programming languages, the user doesn't
  354.      care when the destructor is called.  It just happens when it's supposed
  355.      to.  In low-level languages without any GC at all, there's no way to
  356.      depend on this happening at the right time, so the programmer must
  357.      explicitly call the destructor to clean up memory and state, crossing
  358.      their fingers that it's the right time to do so.   Unlike C++, an object
  359.      destructor is nearly never needed in Perl, and even when it is, explicit
  360.      invocation is uncalled for.  In the case of our Person class, we don't
  361.      need a destructor because Perl takes care of simple matters like memory
  362.      deallocation.
  363.  
  364.      The only situation where Perl's reference-based GC won't work is when
  365.      there's a circularity in the data structure, such as:
  366.  
  367.          $this->{WHATEVER} = $this;
  368.  
  369.      In that case, you must delete the self-reference manually if you expect
  370.      your program not to leak memory.  While admittedly error-prone, this is
  371.      the best we can do right now.  Nonetheless, rest assured that when your
  372.      program is finished, its objects' destructors are all duly called.  So
  373.      you are guaranteed that an object _e_v_e_n_t_u_a_l_l_y gets properly destroyed,
  374.      except in the unique case of a program that never exits.  (If you're
  375.      running Perl embedded in another application, this full GC pass happens a
  376.      bit more frequently--whenever a thread shuts down.)
  377.  
  378.      OOOOtttthhhheeeerrrr OOOObbbbjjjjeeeecccctttt MMMMeeeetttthhhhooooddddssss
  379.  
  380.      The methods we've talked about so far have either been constructors or
  381.      else simple "data methods", interfaces to data stored in the object.
  382.      These are a bit like an object's data members in the C++ world, except
  383.      that strangers don't access them as data.  Instead, they should only
  384.      access the object's data indirectly via its methods.  This is an
  385.      important rule: in Perl, access to an object's data should _o_n_l_y be made
  386.      through methods.
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  401.  
  402.  
  403.  
  404.      Perl doesn't impose restrictions on who gets to use which methods.  The
  405.      public-versus-private distinction is by convention, not syntax.  (Well,
  406.      unless you use the Alias module described below in the section on _D_a_t_a
  407.      _M_e_m_b_e_r_s _a_s _V_a_r_i_a_b_l_e_s.)  Occasionally you'll see method names beginning or
  408.      ending with an underscore or two.  This marking is a convention
  409.      indicating that the methods are private to that class alone and sometimes
  410.      to its closest acquaintances, its immediate subclasses.  But this
  411.      distinction is not enforced by Perl itself.  It's up to the programmer to
  412.      behave.
  413.  
  414.      There's no reason to limit methods to those that simply access data.
  415.      Methods can do anything at all.  The key point is that they're invoked
  416.      against an object or a class.  Let's say we'd like object methods that do
  417.      more than fetch or set one particular field.
  418.  
  419.          sub exclaim {
  420.              my $self = shift;
  421.              return sprintf "Hi, I'm %s, age %d, working with %s",
  422.                  $self->{NAME}, $self->{AGE}, join(", ", $self->{PEERS});
  423.          }
  424.  
  425.      Or maybe even one like this:
  426.  
  427.          sub happy_birthday {
  428.              my $self = shift;
  429.              return ++$self->{AGE};
  430.          }
  431.  
  432.      Some might argue that one should go at these this way:
  433.  
  434.          sub exclaim {
  435.              my $self = shift;
  436.              return sprintf "Hi, I'm %s, age %d, working with %s",
  437.                  $self->name, $self->age, join(", ", $self->peers);
  438.          }
  439.  
  440.          sub happy_birthday {
  441.              my $self = shift;
  442.              return $self->age( $self->age() + 1 );
  443.          }
  444.  
  445.      But since these methods are all executing in the class itself, this may
  446.      not be critical.  There are tradeoffs to be made.  Using direct hash
  447.      access is faster (about an order of magnitude faster, in fact), and it's
  448.      more convenient when you want to interpolate in strings.  But using
  449.      methods (the external interface) internally shields not just the users of
  450.      your class but even you yourself from changes in your data
  451.      representation.
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  467.  
  468.  
  469.  
  470. Class Data
  471.      What about "class data", data items common to each object in a class?
  472.      What would you want that for?  Well, in your Person class, you might like
  473.      to keep track of the total people alive.  How do you implement that?
  474.  
  475.      You _c_o_u_l_d make it a global variable called $Person::Census.  But about
  476.      only reason you'd do that would be if you _w_a_n_t_e_d people to be able to get
  477.      at your class data directly.  They could just say $Person::Census and
  478.      play around with it.  Maybe this is ok in your design scheme.  You might
  479.      even conceivably want to make it an exported variable.  To be exportable,
  480.      a variable must be a (package) global.  If this were a traditional module
  481.      rather than an object-oriented one, you might do that.
  482.  
  483.      While this approach is expected in most traditional modules, it's
  484.      generally considered rather poor form in most object modules.  In an
  485.      object module, you should set up a protective veil to separate interface
  486.      from implementation.  So provide a class method to access class data just
  487.      as you provide object methods to access object data.
  488.  
  489.      So, you _c_o_u_l_d still keep $Census as a package global and rely upon others
  490.      to honor the contract of the module and therefore not play around with
  491.      its implementation.  You could even be supertricky and make $Census a
  492.      tied object as described in the _p_e_r_l_t_i_e manpage, thereby intercepting all
  493.      accesses.
  494.  
  495.      But more often than not, you just want to make your class data a file-
  496.      scoped lexical.  To do so, simply put this at the top of the file:
  497.  
  498.          my $Census = 0;
  499.  
  500.      Even though the scope of a _m_y() normally expires when the block in which
  501.      it was declared is done (in this case the whole file being required or
  502.      used), Perl's deep binding of lexical variables guarantees that the
  503.      variable will not be deallocated, remaining accessible to functions
  504.      declared within that scope.  This doesn't work with global variables
  505.      given temporary values via _l_o_c_a_l(), though.
  506.  
  507.      Irrespective of whether you leave $Census a package global or make it
  508.      instead a file-scoped lexical, you should make these changes to your
  509.      _P_e_r_s_o_n::_n_e_w() constructor:
  510.  
  511.          sub new {
  512.              my $proto = shift;
  513.              my $class = ref($proto) || $proto;
  514.              my $self  = {};
  515.              $Census++;
  516.              $self->{NAME}   = undef;
  517.              $self->{AGE}    = undef;
  518.              $self->{PEERS}  = [];
  519.              bless ($self, $class);
  520.              return $self;
  521.          }
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  533.  
  534.  
  535.  
  536.          sub population {
  537.              return $Census;
  538.          }
  539.  
  540.      Now that we've done this, we certainly do need a destructor so that when
  541.      Person is destroyed, the $Census goes down.  Here's how this could be
  542.      done:
  543.  
  544.          sub DESTROY { --$Census }
  545.  
  546.      Notice how there's no memory to deallocate in the destructor?  That's
  547.      something that Perl takes care of for you all by itself.
  548.  
  549.      AAAAcccccccceeeessssssssiiiinnnngggg CCCCllllaaaassssssss DDDDaaaattttaaaa
  550.  
  551.      It turns out that this is not really a good way to go about handling
  552.      class data.  A good scalable rule is that _y_o_u _m_u_s_t _n_e_v_e_r _r_e_f_e_r_e_n_c_e _c_l_a_s_s
  553.      _d_a_t_a _d_i_r_e_c_t_l_y _f_r_o_m _a_n _o_b_j_e_c_t _m_e_t_h_o_d.  Otherwise you aren't building a
  554.      scalable, inheritable class.  The object must be the rendezvous point for
  555.      all operations, especially from an object method.  The globals (class
  556.      data) would in some sense be in the "wrong" package in your derived
  557.      classes.  In Perl, methods execute in the context of the class they were
  558.      defined in, _n_o_t that of the object that triggered them.  Therefore,
  559.      namespace visibility of package globals in methods is unrelated to
  560.      inheritance.
  561.  
  562.      Got that?  Maybe not.  Ok, let's say that some other class "borrowed"
  563.      (well, inherited) the DESTROY method as it was defined above.  When those
  564.      objects are destroyed, the original $Census variable will be altered, not
  565.      the one in the new class's package namespace.  Perhaps this is what you
  566.      want, but probably it isn't.
  567.  
  568.      Here's how to fix this.  We'll store a reference to the data in the value
  569.      accessed by the hash key "_CENSUS".  Why the underscore?  Well, mostly
  570.      because an initial underscore already conveys strong feelings of
  571.      magicalness to a C programmer.  It's really just a mnemonic device to
  572.      remind ourselves that this field is special and not to be used as a
  573.      public data member in the same way that NAME, AGE, and PEERS are.
  574.      (Because we've been developing this code under the strict pragma, prior
  575.      to perl version 5.004 we'll have to quote the field name.)
  576.  
  577.  
  578.  
  579.  
  580.  
  581.  
  582.  
  583.  
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  599.  
  600.  
  601.  
  602.          sub new {
  603.              my $proto = shift;
  604.              my $class = ref($proto) || $proto;
  605.              my $self  = {};
  606.              $self->{NAME}     = undef;
  607.              $self->{AGE}      = undef;
  608.              $self->{PEERS}    = [];
  609.              # "private" data
  610.              $self->{"_CENSUS"} = \$Census;
  611.              bless ($self, $class);
  612.              ++ ${ $self->{"_CENSUS"} };
  613.              return $self;
  614.          }
  615.  
  616.          sub population {
  617.              my $self = shift;
  618.              if (ref $self) {
  619.                  return ${ $self->{"_CENSUS"} };
  620.              } else {
  621.                  return $Census;
  622.              }
  623.          }
  624.  
  625.          sub DESTROY {
  626.              my $self = shift;
  627.              -- ${ $self->{"_CENSUS"} };
  628.          }
  629.  
  630.  
  631.      DDDDeeeebbbbuuuuggggggggiiiinnnngggg MMMMeeeetttthhhhooooddddssss
  632.  
  633.      It's common for a class to have a debugging mechanism.  For example, you
  634.      might want to see when objects are created or destroyed.  To do that, add
  635.      a debugging variable as a file-scoped lexical.  For this, we'll pull in
  636.      the standard Carp module to emit our warnings and fatal messages.  That
  637.      way messages will come out with the caller's filename and line number
  638.      instead of our own; if we wanted them to be from our own perspective,
  639.      we'd just use _d_i_e() and _w_a_r_n() directly instead of _c_r_o_a_k() and _c_a_r_p()
  640.      respectively.
  641.  
  642.          use Carp;
  643.          my $Debugging = 0;
  644.  
  645.      Now add a new class method to access the variable.
  646.  
  647.          sub debug {
  648.              my $class = shift;
  649.              if (ref $class)  { confess "Class method called as object method" }
  650.              unless (@_ == 1) { confess "usage: CLASSNAME->debug(level)" }
  651.              $Debugging = shift;
  652.          }
  653.  
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  665.  
  666.  
  667.  
  668.      Now fix up DESTROY to murmur a bit as the moribund object expires:
  669.  
  670.          sub DESTROY {
  671.              my $self = shift;
  672.              if ($Debugging) { carp "Destroying $self " . $self->name }
  673.              -- ${ $self->{"_CENSUS"} };
  674.          }
  675.  
  676.      One could conceivably make a per-object debug state.  That way you could
  677.      call both of these:
  678.  
  679.          Person->debug(1);   # entire class
  680.          $him->debug(1);     # just this object
  681.  
  682.      To do so, we need our debugging method to be a "bimodal" one, one that
  683.      works on both classes _a_n_d objects.  Therefore, adjust the _d_e_b_u_g() and
  684.      DESTROY methods as follows:
  685.  
  686.          sub debug {
  687.              my $self = shift;
  688.              confess "usage: thing->debug(level)"    unless @_ == 1;
  689.              my $level = shift;
  690.              if (ref($self))  {
  691.                  $self->{"_DEBUG"} = $level;         # just myself
  692.              } else {
  693.                  $Debugging        = $level;         # whole class
  694.              }
  695.          }
  696.  
  697.          sub DESTROY {
  698.              my $self = shift;
  699.              if ($Debugging || $self->{"_DEBUG"}) {
  700.                  carp "Destroying $self " . $self->name;
  701.              }
  702.              -- ${ $self->{"_CENSUS"} };
  703.          }
  704.  
  705.      What happens if a derived class (which we'll call Employee) inherits
  706.      methods from this Person base class?  Then Employee->debug(), when called
  707.      as a class method, manipulates $Person::Debugging not
  708.      $Employee::Debugging.
  709.  
  710.      CCCCllllaaaassssssss DDDDeeeessssttttrrrruuuuccccttttoooorrrrssss
  711.  
  712.      The object destructor handles the death of each distinct object.  But
  713.      sometimes you want a bit of cleanup when the entire class is shut down,
  714.      which currently only happens when the program exits.  To make such a
  715.      _c_l_a_s_s _d_e_s_t_r_u_c_t_o_r, create a function in that class's package named END.
  716.      This works just like the END function in traditional modules, meaning
  717.      that it gets called whenever your program exits unless it execs or dies
  718.      of an uncaught signal.  For example,
  719.  
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  731.  
  732.  
  733.  
  734.          sub END {
  735.              if ($Debugging) {
  736.                  print "All persons are going away now.\n";
  737.              }
  738.          }
  739.  
  740.      When the program exits, all the class destructors (END functions) are be
  741.      called in the opposite order that they were loaded in (LIFO order).
  742.  
  743.      DDDDooooccccuuuummmmeeeennnnttttiiiinnnngggg tttthhhheeee IIIInnnntttteeeerrrrffffaaaacccceeee
  744.  
  745.      And there you have it: we've just shown you the _i_m_p_l_e_m_e_n_t_a_t_i_o_n of this
  746.      Person class.  Its _i_n_t_e_r_f_a_c_e would be its documentation.  Usually this
  747.      means putting it in pod ("plain old documentation") format right there in
  748.      the same file.  In our Person example, we would place the following docs
  749.      anywhere in the Person.pm file.  Even though it looks mostly like code,
  750.      it's not.  It's embedded documentation such as would be used by the
  751.      pod2man, pod2html, or pod2text programs.  The Perl compiler ignores pods
  752.      entirely, just as the translators ignore code.  Here's an example of some
  753.      pods describing the informal interface:
  754.  
  755.          =head1 NAME
  756.  
  757.          Person - class to implement people
  758.  
  759.          =head1 SYNOPSIS
  760.  
  761.           use Person;
  762.  
  763.           #################
  764.           # class methods #
  765.           #################
  766.           $ob    = Person->new;
  767.           $count = Person->population;
  768.  
  769.           #######################
  770.           # object data methods #
  771.           #######################
  772.  
  773.           ### get versions ###
  774.               $who   = $ob->name;
  775.               $years = $ob->age;
  776.               @pals  = $ob->peers;
  777.  
  778.           ### set versions ###
  779.               $ob->name("Jason");
  780.               $ob->age(23);
  781.               $ob->peers( "Norbert", "Rhys", "Phineas" );
  782.  
  783.           ########################
  784.           # other object methods #
  785.           ########################
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  797.  
  798.  
  799.  
  800.           $phrase = $ob->exclaim;
  801.           $ob->happy_birthday;
  802.  
  803.          =head1 DESCRIPTION
  804.  
  805.          The Person class implements dah dee dah dee dah....
  806.  
  807.      That's all there is to the matter of interface versus implementation.  A
  808.      programmer who opens up the module and plays around with all the private
  809.      little shiny bits that were safely locked up behind the interface
  810.      contract has voided the warranty, and you shouldn't worry about their
  811.      fate.
  812.  
  813. AAAAggggggggrrrreeeeggggaaaattttiiiioooonnnn
  814.      Suppose you later want to change the class to implement better names.
  815.      Perhaps you'd like to support both given names (called Christian names,
  816.      irrespective of one's religion) and family names (called surnames), plus
  817.      nicknames and titles.  If users of your Person class have been properly
  818.      accessing it through its documented interface, then you can easily change
  819.      the underlying implementation.  If they haven't, then they lose and it's
  820.      their fault for breaking the contract and voiding their warranty.
  821.  
  822.      To do this, we'll make another class, this one called Fullname.  What's
  823.      the Fullname class look like?  To answer that question, you have to first
  824.      figure out how you want to use it.  How about we use it this way:
  825.  
  826.          $him = Person->new();
  827.          $him->fullname->title("St");
  828.          $him->fullname->christian("Thomas");
  829.          $him->fullname->surname("Aquinas");
  830.          $him->fullname->nickname("Tommy");
  831.          printf "His normal name is %s\n", $him->name;
  832.          printf "But his real name is %s\n", $him->fullname->as_string;
  833.  
  834.      Ok.  To do this, we'll change _P_e_r_s_o_n::_n_e_w() so that it supports a full
  835.      name field this way:
  836.  
  837.          sub new {
  838.              my $proto = shift;
  839.              my $class = ref($proto) || $proto;
  840.              my $self  = {};
  841.              $self->{FULLNAME} = Fullname->new();
  842.              $self->{AGE}      = undef;
  843.              $self->{PEERS}    = [];
  844.              $self->{"_CENSUS"} = \$Census;
  845.              bless ($self, $class);
  846.              ++ ${ $self->{"_CENSUS"} };
  847.              return $self;
  848.          }
  849.  
  850.  
  851.  
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  863.  
  864.  
  865.  
  866.          sub fullname {
  867.              my $self = shift;
  868.              return $self->{FULLNAME};
  869.          }
  870.  
  871.      Then to support old code, define _P_e_r_s_o_n::_n_a_m_e() this way:
  872.  
  873.          sub name {
  874.              my $self = shift;
  875.              return $self->{FULLNAME}->nickname(@_)
  876.                ||   $self->{FULLNAME}->christian(@_);
  877.          }
  878.  
  879.      Here's the Fullname class.  We'll use the same technique of using a hash
  880.      reference to hold data fields, and methods by the appropriate name to
  881.      access them:
  882.  
  883.          package Fullname;
  884.          use strict;
  885.  
  886.          sub new {
  887.              my $proto = shift;
  888.              my $class = ref($proto) || $proto;
  889.              my $self  = {
  890.                  TITLE       => undef,
  891.                  CHRISTIAN   => undef,
  892.                  SURNAME     => undef,
  893.                  NICK        => undef,
  894.              };
  895.              bless ($self, $class);
  896.              return $self;
  897.          }
  898.  
  899.          sub christian {
  900.              my $self = shift;
  901.              if (@_) { $self->{CHRISTIAN} = shift }
  902.              return $self->{CHRISTIAN};
  903.          }
  904.  
  905.          sub surname {
  906.              my $self = shift;
  907.              if (@_) { $self->{SURNAME} = shift }
  908.              return $self->{SURNAME};
  909.          }
  910.  
  911.          sub nickname {
  912.              my $self = shift;
  913.              if (@_) { $self->{NICK} = shift }
  914.              return $self->{NICK};
  915.          }
  916.  
  917.  
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  929.  
  930.  
  931.  
  932.          sub title {
  933.              my $self = shift;
  934.              if (@_) { $self->{TITLE} = shift }
  935.              return $self->{TITLE};
  936.          }
  937.  
  938.          sub as_string {
  939.              my $self = shift;
  940.              my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
  941.              if ($self->{TITLE}) {
  942.                  $name = $self->{TITLE} . " " . $name;
  943.              }
  944.              return $name;
  945.          }
  946.  
  947.          1;
  948.  
  949.      Finally, here's the test program:
  950.  
  951.          #!/usr/bin/perl -w
  952.          use strict;
  953.          use Person;
  954.          sub END { show_census() }
  955.  
  956.          sub show_census ()  {
  957.              printf "Current population: %d\n", Person->population;
  958.          }
  959.  
  960.          Person->debug(1);
  961.  
  962.          show_census();
  963.  
  964.          my $him = Person->new();
  965.  
  966.          $him->fullname->christian("Thomas");
  967.          $him->fullname->surname("Aquinas");
  968.          $him->fullname->nickname("Tommy");
  969.          $him->fullname->title("St");
  970.          $him->age(1);
  971.  
  972.          printf "%s is really %s.\n", $him->name, $him->fullname;
  973.          printf "%s's age: %d.\n", $him->name, $him->age;
  974.          $him->happy_birthday;
  975.          printf "%s's age: %d.\n", $him->name, $him->age;
  976.  
  977.          show_census();
  978.  
  979.  
  980. IIIInnnnhhhheeeerrrriiiittttaaaannnncccceeee
  981.      Object-oriented programming systems all support some notion of
  982.      inheritance.  Inheritance means allowing one class to piggy-back on top
  983.      of another one so you don't have to write the same code again and again.
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  995.  
  996.  
  997.  
  998.      It's about software reuse, and therefore related to Laziness, the
  999.      principal virtue of a programmer.  (The import/export mechanisms in
  1000.      traditional modules are also a form of code reuse, but a simpler one than
  1001.      the true inheritance that you find in object modules.)
  1002.  
  1003.      Sometimes the syntax of inheritance is built into the core of the
  1004.      language, and sometimes it's not.  Perl has no special syntax for
  1005.      specifying the class (or classes) to inherit from.  Instead, it's all
  1006.      strictly in the semantics.  Each package can have a variable called @ISA,
  1007.      which governs (method) inheritance.  If you try to call a method on an
  1008.      object or class, and that method is not found in that object's package,
  1009.      Perl then looks to @ISA for other packages to go looking through in
  1010.      search of the missing method.
  1011.  
  1012.      Like the special per-package variables recognized by Exporter (such as
  1013.      @EXPORT, @EXPORT_OK, @EXPORT_FAIL, %EXPORT_TAGS, and $VERSION), the @ISA
  1014.      array _m_u_s_t be a package-scoped global and not a file-scoped lexical
  1015.      created via _m_y().  Most classes have just one item in their @ISA array.
  1016.      In this case, we have what's called "single inheritance", or SI for
  1017.      short.
  1018.  
  1019.      Consider this class:
  1020.  
  1021.          package Employee;
  1022.          use Person;
  1023.          @ISA = ("Person");
  1024.          1;
  1025.  
  1026.      Not a lot to it, eh?  All it's doing so far is loading in another class
  1027.      and stating that this one will inherit methods from that other class if
  1028.      need be.  We have given it none of its own methods.  We rely upon an
  1029.      Employee to behave just like a Person.
  1030.  
  1031.      Setting up an empty class like this is called the "empty subclass test";
  1032.      that is, making a derived class that does nothing but inherit from a base
  1033.      class.  If the original base class has been designed properly, then the
  1034.      new derived class can be used as a drop-in replacement for the old one.
  1035.      This means you should be able to write a program like this:
  1036.  
  1037.          use Employee;
  1038.          my $empl = Employee->new();
  1039.          $empl->name("Jason");
  1040.          $empl->age(23);
  1041.          printf "%s is age %d.\n", $empl->name, $empl->age;
  1042.  
  1043.      By proper design, we mean always using the two-argument form of _b_l_e_s_s(),
  1044.      avoiding direct access of global data, and not exporting anything.  If
  1045.      you look back at the _P_e_r_s_o_n::_n_e_w() function we defined above, we were
  1046.      careful to do that.  There's a bit of package data used in the
  1047.      constructor, but the reference to this is stored on the object itself and
  1048.      all other methods access package data via that reference, so we should be
  1049.      ok.
  1050.  
  1051.  
  1052.  
  1053.                                                                        PPPPaaaaggggeeee 11116666
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1061.  
  1062.  
  1063.  
  1064.      What do we mean by the _P_e_r_s_o_n::_n_e_w() function -- isn't that actually a
  1065.      method?  Well, in principle, yes.  A method is just a function that
  1066.      expects as its first argument a class name (package) or object (blessed
  1067.      reference).   _P_e_r_s_o_n::_n_e_w() is the function that both the Person->new()
  1068.      method and the Employee->new() method end up calling.  Understand that
  1069.      while a method call looks a lot like a function call, they aren't really
  1070.      quite the same, and if you treat them as the same, you'll very soon be
  1071.      left with nothing but broken programs.  First, the actual underlying
  1072.      calling conventions are different: method calls get an extra argument.
  1073.      Second, function calls don't do inheritance, but methods do.
  1074.  
  1075.              Method Call             Resulting Function Call
  1076.              -----------             ------------------------
  1077.              Person->new()           Person::new("Person")
  1078.              Employee->new()         Person::new("Employee")
  1079.  
  1080.      So don't use function calls when you mean to call a method.
  1081.  
  1082.      If an employee is just a Person, that's not all too very interesting.  So
  1083.      let's add some other methods.  We'll give our employee data fields to
  1084.      access their salary, their employee ID, and their start date.
  1085.  
  1086.      If you're getting a little tired of creating all these nearly identical
  1087.      methods just to get at the object's data, do not despair.  Later, we'll
  1088.      describe several different convenience mechanisms for shortening this up.
  1089.      Meanwhile, here's the straight-forward way:
  1090.  
  1091.          sub salary {
  1092.              my $self = shift;
  1093.              if (@_) { $self->{SALARY} = shift }
  1094.              return $self->{SALARY};
  1095.          }
  1096.  
  1097.          sub id_number {
  1098.              my $self = shift;
  1099.              if (@_) { $self->{ID} = shift }
  1100.              return $self->{ID};
  1101.          }
  1102.  
  1103.          sub start_date {
  1104.              my $self = shift;
  1105.              if (@_) { $self->{START_DATE} = shift }
  1106.              return $self->{START_DATE};
  1107.          }
  1108.  
  1109.  
  1110.      OOOOvvvveeeerrrrrrrriiiiddddddddeeeennnn MMMMeeeetttthhhhooooddddssss
  1111.  
  1112.      What happens when both a derived class and its base class have the same
  1113.      method defined?  Well, then you get the derived class's version of that
  1114.      method.  For example, let's say that we want the _p_e_e_r_s() method called on
  1115.      an employee to act a bit differently.  Instead of just returning the list
  1116.  
  1117.  
  1118.  
  1119.                                                                        PPPPaaaaggggeeee 11117777
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1127.  
  1128.  
  1129.  
  1130.      of peer names, let's return slightly different strings.  So doing this:
  1131.  
  1132.          $empl->peers("Peter", "Paul", "Mary");
  1133.          printf "His peers are: %s\n", join(", ", $empl->peers);
  1134.  
  1135.      will produce:
  1136.  
  1137.          His peers are: PEON=PETER, PEON=PAUL, PEON=MARY
  1138.  
  1139.      To do this, merely add this definition into the Employee.pm file:
  1140.  
  1141.          sub peers {
  1142.              my $self = shift;
  1143.              if (@_) { @{ $self->{PEERS} } = @_ }
  1144.              return map { "PEON=\U$_" } @{ $self->{PEERS} };
  1145.          }
  1146.  
  1147.      There, we've just demonstrated the high-falutin' concept known in certain
  1148.      circles as _p_o_l_y_m_o_r_p_h_i_s_m.  We've taken on the form and behaviour of an
  1149.      existing object, and then we've altered it to suit our own purposes.
  1150.      This is a form of Laziness.  (Getting polymorphed is also what happens
  1151.      when the wizard decides you'd look better as a frog.)
  1152.  
  1153.      Every now and then you'll want to have a method call trigger both its
  1154.      derived class (also known as "subclass") version as well as its base
  1155.      class (also known as "superclass") version.  In practice, constructors
  1156.      and destructors are likely to want to do this, and it probably also makes
  1157.      sense in the _d_e_b_u_g() method we showed previously.
  1158.  
  1159.      To do this, add this to Employee.pm:
  1160.  
  1161.          use Carp;
  1162.          my $Debugging = 0;
  1163.  
  1164.          sub debug {
  1165.              my $self = shift;
  1166.              confess "usage: thing->debug(level)"    unless @_ == 1;
  1167.              my $level = shift;
  1168.              if (ref($self))  {
  1169.                  $self->{"_DEBUG"} = $level;
  1170.              } else {
  1171.                  $Debugging = $level;            # whole class
  1172.              }
  1173.              Person::debug($self, $Debugging);   # don't really do this
  1174.          }
  1175.  
  1176.      As you see, we turn around and call the Person package's _d_e_b_u_g()
  1177.      function.  But this is far too fragile for good design.  What if Person
  1178.      doesn't have a _d_e_b_u_g() function, but is inheriting _i_t_s _d_e_b_u_g() method
  1179.      from elsewhere?  It would have been slightly better to say
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.                                                                        PPPPaaaaggggeeee 11118888
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1193.  
  1194.  
  1195.  
  1196.          Person->debug($Debugging);
  1197.  
  1198.      But even that's got too much hard-coded.  It's somewhat better to say
  1199.  
  1200.          $self->Person::debug($Debugging);
  1201.  
  1202.      Which is a funny way to say to start looking for a _d_e_b_u_g() method up in
  1203.      Person.  This strategy is more often seen on overridden object methods
  1204.      than on overridden class methods.
  1205.  
  1206.      There is still something a bit off here.  We've hard-coded our
  1207.      superclass's name.  This in particular is bad if you change which classes
  1208.      you inherit from, or add others.  Fortunately, the pseudoclass SUPER
  1209.      comes to the rescue here.
  1210.  
  1211.          $self->SUPER::debug($Debugging);
  1212.  
  1213.      This way it starts looking in my class's @ISA.  This only makes sense
  1214.      from _w_i_t_h_i_n a method call, though.  Don't try to access anything in
  1215.      SUPER:: from anywhere else, because it doesn't exist outside an
  1216.      overridden method call.
  1217.  
  1218.      Things are getting a bit complicated here.  Have we done anything we
  1219.      shouldn't?  As before, one way to test whether we're designing a decent
  1220.      class is via the empty subclass test.  Since we already have an Employee
  1221.      class that we're trying to check, we'd better get a new empty subclass
  1222.      that can derive from Employee.  Here's one:
  1223.  
  1224.          package Boss;
  1225.          use Employee;        # :-)
  1226.          @ISA = qw(Employee);
  1227.  
  1228.      And here's the test program:
  1229.  
  1230.          #!/usr/bin/perl -w
  1231.          use strict;
  1232.          use Boss;
  1233.          Boss->debug(1);
  1234.  
  1235.          my $boss = Boss->new();
  1236.  
  1237.          $boss->fullname->title("Don");
  1238.          $boss->fullname->surname("Pichon Alvarez");
  1239.          $boss->fullname->christian("Federico Jesus");
  1240.          $boss->fullname->nickname("Fred");
  1241.  
  1242.          $boss->age(47);
  1243.          $boss->peers("Frank", "Felipe", "Faust");
  1244.  
  1245.          printf "%s is age %d.\n", $boss->fullname, $boss->age;
  1246.          printf "His peers are: %s\n", join(", ", $boss->peers);
  1247.  
  1248.  
  1249.  
  1250.  
  1251.                                                                        PPPPaaaaggggeeee 11119999
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1259.  
  1260.  
  1261.  
  1262.      Running it, we see that we're still ok.  If you'd like to dump out your
  1263.      object in a nice format, somewhat like the way the 'x' command works in
  1264.      the debugger, you could use the Data::Dumper module from CPAN this way:
  1265.  
  1266.          use Data::Dumper;
  1267.          print "Here's the boss:\n";
  1268.          print Dumper($boss);
  1269.  
  1270.      Which shows us something like this:
  1271.  
  1272.          Here's the boss:
  1273.          $VAR1 = bless( {
  1274.               _CENSUS => \1,
  1275.               FULLNAME => bless( {
  1276.                                    TITLE => 'Don',
  1277.                                    SURNAME => 'Pichon Alvarez',
  1278.                                    NICK => 'Fred',
  1279.                                    CHRISTIAN => 'Federico Jesus'
  1280.                                  }, 'Fullname' ),
  1281.               AGE => 47,
  1282.               PEERS => [
  1283.                          'Frank',
  1284.                          'Felipe',
  1285.                          'Faust'
  1286.                        ]
  1287.             }, 'Boss' );
  1288.  
  1289.      Hm.... something's missing there.  What about the salary, start date, and
  1290.      ID fields?  Well, we never set them to anything, even undef, so they
  1291.      don't show up in the hash's keys.  The Employee class has no _n_e_w() method
  1292.      of its own, and the _n_e_w() method in Person doesn't know about Employees.
  1293.      (Nor should it: proper OO design dictates that a subclass be allowed to
  1294.      know about its immediate superclass, but never vice-versa.)  So let's fix
  1295.      up _E_m_p_l_o_y_e_e::_n_e_w() this way:
  1296.  
  1297.          sub new {
  1298.              my $proto = shift;
  1299.              my $class = ref($proto) || $proto;
  1300.              my $self  = $class->SUPER::new();
  1301.              $self->{SALARY}        = undef;
  1302.              $self->{ID}            = undef;
  1303.              $self->{START_DATE}    = undef;
  1304.              bless ($self, $class);          # reconsecrate
  1305.              return $self;
  1306.          }
  1307.  
  1308.      Now if you dump out an Employee or Boss object, you'll find that new
  1309.      fields show up there now.
  1310.  
  1311.  
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.                                                                        PPPPaaaaggggeeee 22220000
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1325.  
  1326.  
  1327.  
  1328.      MMMMuuuullllttttiiiipppplllleeee IIIInnnnhhhheeeerrrriiiittttaaaannnncccceeee
  1329.  
  1330.      Ok, at the risk of confusing beginners and annoying OO gurus, it's time
  1331.      to confess that Perl's object system includes that controversial notion
  1332.      known as multiple inheritance, or MI for short.  All this means is that
  1333.      rather than having just one parent class who in turn might itself have a
  1334.      parent class, etc., that you can directly inherit from two or more
  1335.      parents.  It's true that some uses of MI can get you into trouble,
  1336.      although hopefully not quite so much trouble with Perl as with
  1337.      dubiously-OO languages like C++.
  1338.  
  1339.      The way it works is actually pretty simple: just put more than one
  1340.      package name in your @ISA array.  When it comes time for Perl to go
  1341.      finding methods for your object, it looks at each of these packages in
  1342.      order.  Well, kinda.  It's actually a fully recursive, depth-first order.
  1343.      Consider a bunch of @ISA arrays like this:
  1344.  
  1345.          @First::ISA    = qw( Alpha );
  1346.          @Second::ISA   = qw( Beta );
  1347.          @Third::ISA    = qw( First Second );
  1348.  
  1349.      If you have an object of class Third:
  1350.  
  1351.          my $ob = Third->new();
  1352.          $ob->spin();
  1353.  
  1354.      How do we find a _s_p_i_n() method (or a _n_e_w() method for that matter)?
  1355.      Because the search is depth-first, classes will be looked up in the
  1356.      following order: Third, First, Alpha, Second, and Beta.
  1357.  
  1358.      In practice, few class modules have been seen that actually make use of
  1359.      MI.  One nearly always chooses simple containership of one class within
  1360.      another over MI.  That's why our Person object _c_o_n_t_a_i_n_e_d a Fullname
  1361.      object.  That doesn't mean it _w_a_s one.
  1362.  
  1363.      However, there is one particular area where MI in Perl is rampant:
  1364.      borrowing another class's class methods.  This is rather common,
  1365.      especially with some bundled "objectless" classes, like Exporter,
  1366.      DynaLoader, AutoLoader, and SelfLoader.  These classes do not provide
  1367.      constructors; they exist only so you may inherit their class methods.
  1368.      (It's not entirely clear why inheritance was done here rather than
  1369.      traditional module importation.)
  1370.  
  1371.      For example, here is the POSIX module's @ISA:
  1372.  
  1373.          package POSIX;
  1374.          @ISA = qw(Exporter DynaLoader);
  1375.  
  1376.      The POSIX module isn't really an object module, but then, neither are
  1377.      Exporter or DynaLoader.  They're just lending their classes' behaviours
  1378.      to POSIX.
  1379.  
  1380.  
  1381.  
  1382.  
  1383.                                                                        PPPPaaaaggggeeee 22221111
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1391.  
  1392.  
  1393.  
  1394.      Why don't people use MI for object methods much?  One reason is that it
  1395.      can have complicated side-effects.  For one thing, your inheritance graph
  1396.      (no longer a tree) might converge back to the same base class.  Although
  1397.      Perl guards against recursive inheritance, merely having parents who are
  1398.      related to each other via a common ancestor, incestuous though it sounds,
  1399.      is not forbidden.  What if in our Third class shown above we wanted its
  1400.      _n_e_w() method to also call both overridden constructors in its two parent
  1401.      classes?  The SUPER notation would only find the first one.  Also, what
  1402.      about if the Alpha and Beta classes both had a common ancestor, like
  1403.      Nought?  If you kept climbing up the inheritance tree calling overridden
  1404.      methods, you'd end up calling _N_o_u_g_h_t::_n_e_w() twice, which might well be a
  1405.      bad idea.
  1406.  
  1407.      UUUUNNNNIIIIVVVVEEEERRRRSSSSAAAALLLL:::: TTTThhhheeee RRRRooooooootttt ooooffff AAAAllllllll OOOObbbbjjjjeeeeccccttttssss
  1408.  
  1409.      Wouldn't it be convenient if all objects were rooted at some ultimate
  1410.      base class?  That way you could give every object common methods without
  1411.      having to go and add it to each and every @ISA.  Well, it turns out that
  1412.      you can.  You don't see it, but Perl tacitly and irrevocably assumes that
  1413.      there's an extra element at the end of @ISA: the class UNIVERSAL.  In
  1414.      version 5.003, there were no predefined methods there, but you could put
  1415.      whatever you felt like into it.
  1416.  
  1417.      However, as of version 5.004 (or some subversive releases, like
  1418.      5.003_08), UNIVERSAL has some methods in it already.  These are builtin
  1419.      to your Perl binary, so they don't take any extra time to load.
  1420.      Predefined methods include _i_s_a(), _c_a_n(), and _V_E_R_S_I_O_N().  _i_s_a() tells you
  1421.      whether an object or class "is" another one without having to traverse
  1422.      the hierarchy yourself:
  1423.  
  1424.         $has_io = $fd->isa("IO::Handle");
  1425.         $itza_handle = IO::Socket->isa("IO::Handle");
  1426.  
  1427.      The _c_a_n() method, called against that object or class, reports back
  1428.      whether its string argument is a callable method name in that class.  In
  1429.      fact, it gives you back a function reference to that method:
  1430.  
  1431.         $his_print_method = $obj->can('as_string');
  1432.  
  1433.      Finally, the VERSION method checks whether the class (or the object's
  1434.      class) has a package global called $VERSION that's high enough, as in:
  1435.  
  1436.          Some_Module->VERSION(3.0);
  1437.          $his_vers = $ob->VERSION();
  1438.  
  1439.      However, we don't usually call VERSION ourselves.  (Remember that an all
  1440.      uppercase function name is a Perl convention that indicates that the
  1441.      function will be automatically used by Perl in some way.)  In this case,
  1442.      it happens when you say
  1443.  
  1444.  
  1445.  
  1446.  
  1447.  
  1448.  
  1449.                                                                        PPPPaaaaggggeeee 22222222
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1457.  
  1458.  
  1459.  
  1460.          use Some_Module 3.0;
  1461.  
  1462.      If you wanted to add version checking to your Person class explained
  1463.      above, just add this to Person.pm:
  1464.  
  1465.          use vars qw($VERSION);
  1466.          $VERSION = '1.1';
  1467.  
  1468.      and then in Employee.pm could you can say
  1469.  
  1470.          use Employee 1.1;
  1471.  
  1472.      And it would make sure that you have at least that version number or
  1473.      higher available.   This is not the same as loading in that exact version
  1474.      number.  No mechanism currently exists for concurrent installation of
  1475.      multiple versions of a module.  Lamentably.
  1476.  
  1477. AAAAlllltttteeeerrrrnnnnaaaatttteeee OOOObbbbjjjjeeeecccctttt RRRReeeepppprrrreeeesssseeeennnnttttaaaattttiiiioooonnnnssss
  1478.      Nothing requires objects to be implemented as hash references.  An object
  1479.      can be any sort of reference so long as its referent has been suitably
  1480.      blessed.  That means scalar, array, and code references are also fair
  1481.      game.
  1482.  
  1483.      A scalar would work if the object has only one datum to hold.  An array
  1484.      would work for most cases, but makes inheritance a bit dodgy because you
  1485.      have to invent new indices for the derived classes.
  1486.  
  1487.      AAAArrrrrrrraaaayyyyssss aaaassss OOOObbbbjjjjeeeeccccttttssss
  1488.  
  1489.      If the user of your class honors the contract and sticks to the
  1490.      advertised interface, then you can change its underlying interface if you
  1491.      feel like it.  Here's another implementation that conforms to the same
  1492.      interface specification.  This time we'll use an array reference instead
  1493.      of a hash reference to represent the object.
  1494.  
  1495.          package Person;
  1496.          use strict;
  1497.  
  1498.          my($NAME, $AGE, $PEERS) = ( 0 .. 2 );
  1499.  
  1500.          ############################################
  1501.          ## the object constructor (array version) ##
  1502.          ############################################
  1503.          sub new {
  1504.              my $self = [];
  1505.              $self->[$NAME]   = undef;  # this is unnecessary
  1506.              $self->[$AGE]    = undef;  # as is this
  1507.              $self->[$PEERS]  = [];     # but this isn't, really
  1508.              bless($self);
  1509.              return $self;
  1510.          }
  1511.  
  1512.  
  1513.  
  1514.  
  1515.                                                                        PPPPaaaaggggeeee 22223333
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1523.  
  1524.  
  1525.  
  1526.          sub name {
  1527.              my $self = shift;
  1528.              if (@_) { $self->[$NAME] = shift }
  1529.              return $self->[$NAME];
  1530.          }
  1531.  
  1532.          sub age {
  1533.              my $self = shift;
  1534.              if (@_) { $self->[$AGE] = shift }
  1535.              return $self->[$AGE];
  1536.          }
  1537.  
  1538.          sub peers {
  1539.              my $self = shift;
  1540.              if (@_) { @{ $self->[$PEERS] } = @_ }
  1541.              return @{ $self->[$PEERS] };
  1542.          }
  1543.  
  1544.          1;  # so the require or use succeeds
  1545.  
  1546.      You might guess that the array access would be a lot faster than the hash
  1547.      access, but they're actually comparable.  The array is a _l_i_t_t_l_e bit
  1548.      faster, but not more than ten or fifteen percent, even when you replace
  1549.      the variables above like $AGE with literal numbers, like 1.  A bigger
  1550.      difference between the two approaches can be found in memory use.  A hash
  1551.      representation takes up more memory than an array representation because
  1552.      you have to allocate memory for the keys as well as for the values.
  1553.      However, it really isn't that bad, especially since as of version 5.004,
  1554.      memory is only allocated once for a given hash key, no matter how many
  1555.      hashes have that key.  It's expected that sometime in the future, even
  1556.      these differences will fade into obscurity as more efficient underlying
  1557.      representations are devised.
  1558.  
  1559.      Still, the tiny edge in speed (and somewhat larger one in memory) is
  1560.      enough to make some programmers choose an array representation for simple
  1561.      classes.  There's still a little problem with scalability, though,
  1562.      because later in life when you feel like creating subclasses, you'll find
  1563.      that hashes just work out better.
  1564.  
  1565.      CCCClllloooossssuuuurrrreeeessss aaaassss OOOObbbbjjjjeeeeccccttttssss
  1566.  
  1567.      Using a code reference to represent an object offers some fascinating
  1568.      possibilities.  We can create a new anonymous function (closure) who
  1569.      alone in all the world can see the object's data.  This is because we put
  1570.      the data into an anonymous hash that's lexically visible only to the
  1571.      closure we create, bless, and return as the object.  This object's
  1572.      methods turn around and call the closure as a regular subroutine call,
  1573.      passing it the field we want to affect.  (Yes, the double-function call
  1574.      is slow, but if you wanted fast, you wouldn't be using objects at all,
  1575.      eh? :-)
  1576.  
  1577.  
  1578.  
  1579.  
  1580.  
  1581.                                                                        PPPPaaaaggggeeee 22224444
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1589.  
  1590.  
  1591.  
  1592.      Use would be similar to before:
  1593.  
  1594.          use Person;
  1595.          $him = Person->new();
  1596.          $him->name("Jason");
  1597.          $him->age(23);
  1598.          $him->peers( [ "Norbert", "Rhys", "Phineas" ] );
  1599.          printf "%s is %d years old.\n", $him->name, $him->age;
  1600.          print "His peers are: ", join(", ", @{$him->peers}), "\n";
  1601.  
  1602.      but the implementation would be radically, perhaps even sublimely
  1603.      different:
  1604.  
  1605.          package Person;
  1606.  
  1607.          sub new {
  1608.               my $that  = shift;
  1609.               my $class = ref($that) || $that;
  1610.               my $self = {
  1611.                  NAME  => undef,
  1612.                  AGE   => undef,
  1613.                  PEERS => [],
  1614.               };
  1615.               my $closure = sub {
  1616.                  my $field = shift;
  1617.                  if (@_) { $self->{$field} = shift }
  1618.                  return    $self->{$field};
  1619.              };
  1620.              bless($closure, $class);
  1621.              return $closure;
  1622.          }
  1623.  
  1624.          sub name   { &{ $_[0] }("NAME",  @_[ 1 .. $#_ ] ) }
  1625.          sub age    { &{ $_[0] }("AGE",   @_[ 1 .. $#_ ] ) }
  1626.          sub peers  { &{ $_[0] }("PEERS", @_[ 1 .. $#_ ] ) }
  1627.  
  1628.          1;
  1629.  
  1630.      Because this object is hidden behind a code reference, it's probably a
  1631.      bit mysterious to those whose background is more firmly rooted in
  1632.      standard procedural or object-based programming languages than in
  1633.      functional programming languages whence closures derive.  The object
  1634.      created and returned by the _n_e_w() method is itself not a data reference
  1635.      as we've seen before.  It's an anonymous code reference that has within
  1636.      it access to a specific version (lexical binding and instantiation) of
  1637.      the object's data, which are stored in the private variable $self.
  1638.      Although this is the same function each time, it contains a different
  1639.      version of $self.
  1640.  
  1641.      When a method like $him->name("Jason") is called, its implicit zeroth
  1642.      argument is the invoking object--just as it is with all method calls.
  1643.      But in this case, it's our code reference (something like a function
  1644.  
  1645.  
  1646.  
  1647.                                                                        PPPPaaaaggggeeee 22225555
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1655.  
  1656.  
  1657.  
  1658.      pointer in C++, but with deep binding of lexical variables).  There's not
  1659.      a lot to be done with a code reference beyond calling it, so that's just
  1660.      what we do when we say &{$_[0]}.  This is just a regular function call,
  1661.      not a method call.  The initial argument is the string "NAME", and any
  1662.      remaining arguments are whatever had been passed to the method itself.
  1663.  
  1664.      Once we're executing inside the closure that had been created in _n_e_w(),
  1665.      the $self hash reference suddenly becomes visible.  The closure grabs its
  1666.      first argument ("NAME" in this case because that's what the _n_a_m_e() method
  1667.      passed it), and uses that string to subscript into the private hash
  1668.      hidden in its unique version of $self.
  1669.  
  1670.      Nothing under the sun will allow anyone outside the executing method to
  1671.      be able to get at this hidden data.  Well, nearly nothing.  You _c_o_u_l_d
  1672.      single step through the program using the debugger and find out the
  1673.      pieces while you're in the method, but everyone else is out of luck.
  1674.  
  1675.      There, if that doesn't excite the Scheme folks, then I just don't know
  1676.      what will.  Translation of this technique into C++, Java, or any other
  1677.      braindead-static language is left as a futile exercise for aficionados of
  1678.      those camps.
  1679.  
  1680.      You could even add a bit of nosiness via the _c_a_l_l_e_r() function and make
  1681.      the closure refuse to operate unless called via its own package.  This
  1682.      would no doubt satisfy certain fastidious concerns of programming police
  1683.      and related puritans.
  1684.  
  1685.      If you were wondering when Hubris, the third principle virtue of a
  1686.      programmer, would come into play, here you have it. (More seriously,
  1687.      Hubris is just the pride in craftsmanship that comes from having written
  1688.      a sound bit of well-designed code.)
  1689.  
  1690. AAAAUUUUTTTTOOOOLLLLOOOOAAAADDDD:::: PPPPrrrrooooxxxxyyyy MMMMeeeetttthhhhooooddddssss
  1691.      Autoloading is a way to intercept calls to undefined methods.  An
  1692.      autoload routine may choose to create a new function on the fly, either
  1693.      loaded from disk or perhaps just _e_v_a_l()ed right there.  This define-on-
  1694.      the-fly strategy is why it's called autoloading.
  1695.  
  1696.      But that's only one possible approach.  Another one is to just have the
  1697.      autoloaded method itself directly provide the requested service.  When
  1698.      used in this way, you may think of autoloaded methods as "proxy" methods.
  1699.  
  1700.      When Perl tries to call an undefined function in a particular package and
  1701.      that function is not defined, it looks for a function in that same
  1702.      package called AUTOLOAD.  If one exists, it's called with the same
  1703.      arguments as the original function would have had.  The fully-qualified
  1704.      name of the function is stored in that package's global variable
  1705.      $AUTOLOAD.  Once called, the function can do anything it would like,
  1706.      including defining a new function by the right name, and then doing a
  1707.      really fancy kind of goto right to it, erasing itself from the call
  1708.      stack.
  1709.  
  1710.  
  1711.  
  1712.  
  1713.                                                                        PPPPaaaaggggeeee 22226666
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1721.  
  1722.  
  1723.  
  1724.      What does this have to do with objects?  After all, we keep talking about
  1725.      functions, not methods.  Well, since a method is just a function with an
  1726.      extra argument and some fancier semantics about where it's found, we can
  1727.      use autoloading for methods, too.  Perl doesn't start looking for an
  1728.      AUTOLOAD method until it has exhausted the recursive hunt up through
  1729.      @ISA, though.  Some programmers have even been known to define a
  1730.      UNIVERSAL::AUTOLOAD method to trap unresolved method calls to any kind of
  1731.      object.
  1732.  
  1733.      AAAAuuuuttttoooollllooooaaaaddddeeeedddd DDDDaaaattttaaaa MMMMeeeetttthhhhooooddddssss
  1734.  
  1735.      You probably began to get a little suspicious about the duplicated code
  1736.      way back earlier when we first showed you the Person class, and then
  1737.      later the Employee class.  Each method used to access the hash fields
  1738.      looked virtually identical.  This should have tickled that great
  1739.      programming virtue, Impatience, but for the time, we let Laziness win
  1740.      out, and so did nothing.  Proxy methods can cure this.
  1741.  
  1742.      Instead of writing a new function every time we want a new data field,
  1743.      we'll use the autoload mechanism to generate (actually, mimic) methods on
  1744.      the fly.  To verify that we're accessing a valid member, we will check
  1745.      against an _permitted (pronounced "under-permitted") field, which is a
  1746.      reference to a file-scoped lexical (like a C file static) hash of
  1747.      permitted fields in this record called %fields.  Why the underscore?  For
  1748.      the same reason as the _CENSUS field we once used: as a marker that means
  1749.      "for internal use only".
  1750.  
  1751.      Here's what the module initialization code and class constructor will
  1752.      look like when taking this approach:
  1753.  
  1754.          package Person;
  1755.          use Carp;
  1756.          use vars qw($AUTOLOAD);  # it's a package global
  1757.  
  1758.          my %fields = (
  1759.              name        => undef,
  1760.              age         => undef,
  1761.              peers       => undef,
  1762.          );
  1763.  
  1764.          sub new {
  1765.              my $that  = shift;
  1766.              my $class = ref($that) || $that;
  1767.              my $self  = {
  1768.                  _permitted => \%fields,
  1769.                  %fields,
  1770.              };
  1771.              bless $self, $class;
  1772.              return $self;
  1773.          }
  1774.  
  1775.      If we wanted our record to have default values, we could fill those in
  1776.  
  1777.  
  1778.  
  1779.                                                                        PPPPaaaaggggeeee 22227777
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1787.  
  1788.  
  1789.  
  1790.      where current we have undef in the %fields hash.
  1791.  
  1792.      Notice how we saved a reference to our class data on the object itself?
  1793.      Remember that it's important to access class data through the object
  1794.      itself instead of having any method reference %fields directly, or else
  1795.      you won't have a decent inheritance.
  1796.  
  1797.      The real magic, though, is going to reside in our proxy method, which
  1798.      will handle all calls to undefined methods for objects of class Person
  1799.      (or subclasses of Person).  It has to be called AUTOLOAD.  Again, it's
  1800.      all caps because it's called for us implicitly by Perl itself, not by a
  1801.      user directly.
  1802.  
  1803.          sub AUTOLOAD {
  1804.              my $self = shift;
  1805.              my $type = ref($self)
  1806.                          or croak "$self is not an object";
  1807.  
  1808.              my $name = $AUTOLOAD;
  1809.              $name =~ s/.*://;   # strip fully-qualified portion
  1810.  
  1811.              unless (exists $self->{_permitted}->{$name} ) {
  1812.                  croak "Can't access `$name' field in class $type";
  1813.              }
  1814.  
  1815.              if (@_) {
  1816.                  return $self->{$name} = shift;
  1817.              } else {
  1818.                  return $self->{$name};
  1819.              }
  1820.          }
  1821.  
  1822.      Pretty nifty, eh?  All we have to do to add new data fields is modify
  1823.      %fields.  No new functions need be written.
  1824.  
  1825.      I could have avoided the _permitted field entirely, but I wanted to
  1826.      demonstrate how to store a reference to class data on the object so you
  1827.      wouldn't have to access that class data directly from an object method.
  1828.  
  1829.      IIIInnnnhhhheeeerrrriiiitttteeeedddd AAAAuuuuttttoooollllooooaaaaddddeeeedddd DDDDaaaattttaaaa MMMMeeeetttthhhhooooddddssss
  1830.  
  1831.      But what about inheritance?  Can we define our Employee class similarly?
  1832.      Yes, so long as we're careful enough.
  1833.  
  1834.      Here's how to be careful:
  1835.  
  1836.          package Employee;
  1837.          use Person;
  1838.          use strict;
  1839.          use vars qw(@ISA);
  1840.          @ISA = qw(Person);
  1841.  
  1842.  
  1843.  
  1844.  
  1845.                                                                        PPPPaaaaggggeeee 22228888
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1853.  
  1854.  
  1855.  
  1856.          my %fields = (
  1857.              id          => undef,
  1858.              salary      => undef,
  1859.          );
  1860.  
  1861.          sub new {
  1862.              my $that  = shift;
  1863.              my $class = ref($that) || $that;
  1864.              my $self = bless $that->SUPER::new(), $class;
  1865.              my($element);
  1866.              foreach $element (keys %fields) {
  1867.                  $self->{_permitted}->{$element} = $fields{$element};
  1868.              }
  1869.              @{$self}{keys %fields} = values %fields;
  1870.              return $self;
  1871.          }
  1872.  
  1873.      Once we've done this, we don't even need to have an AUTOLOAD function in
  1874.      the Employee package, because we'll grab Person's version of that via
  1875.      inheritance, and it will all work out just fine.
  1876.  
  1877. MMMMeeeettttaaaaccccllllaaaassssssssiiiiccccaaaallll TTTToooooooollllssss
  1878.      Even though proxy methods can provide a more convenient approach to
  1879.      making more struct-like classes than tediously coding up data methods as
  1880.      functions, it still leaves a bit to be desired.  For one thing, it means
  1881.      you have to handle bogus calls that you don't mean to trap via your
  1882.      proxy.  It also means you have to be quite careful when dealing with
  1883.      inheritance, as detailed above.
  1884.  
  1885.      Perl programmers have responded to this by creating several different
  1886.      class construction classes.  These metaclasses are classes that create
  1887.      other classes.  A couple worth looking at are Class::Struct and Alias.
  1888.      These and other related metaclasses can be found in the modules directory
  1889.      on CPAN.
  1890.  
  1891.      CCCCllllaaaassssssss::::::::SSSSttttrrrruuuucccctttt
  1892.  
  1893.      One of the older ones is Class::Struct.  In fact, its syntax and
  1894.      interface were sketched out long before perl5 even solidified into a real
  1895.      thing.  What it does is provide you a way to "declare" a class as having
  1896.      objects whose fields are of a specific type.  The function that does this
  1897.      is called, not surprisingly enough, _s_t_r_u_c_t().  Because structures or
  1898.      records are not base types in Perl, each time you want to create a class
  1899.      to provide a record-like data object, you yourself have to define a _n_e_w()
  1900.      method, plus separate data-access methods for each of that record's
  1901.      fields.  You'll quickly become bored with this process.  The
  1902.      _C_l_a_s_s::_S_t_r_u_c_t::_s_t_r_u_c_t() function alleviates this tedium.
  1903.  
  1904.      Here's a simple example of using it:
  1905.  
  1906.  
  1907.  
  1908.  
  1909.  
  1910.  
  1911.                                                                        PPPPaaaaggggeeee 22229999
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1919.  
  1920.  
  1921.  
  1922.          use Class::Struct qw(struct);
  1923.          use Jobbie;  # user-defined; see below
  1924.  
  1925.          struct 'Fred' => {
  1926.              one        => '$',
  1927.              many       => '@',
  1928.              profession => Jobbie,  # calls Jobbie->new()
  1929.          };
  1930.  
  1931.          $ob = Fred->new;
  1932.          $ob->one("hmmmm");
  1933.  
  1934.          $ob->many(0, "here");
  1935.          $ob->many(1, "you");
  1936.          $ob->many(2, "go");
  1937.          print "Just set: ", $ob->many(2), "\n";
  1938.  
  1939.          $ob->profession->salary(10_000);
  1940.  
  1941.      You can declare types in the struct to be basic Perl types, or user-
  1942.      defined types (classes).  User types will be initialized by calling that
  1943.      class's _n_e_w() method.
  1944.  
  1945.      Here's a real-world example of using struct generation.  Let's say you
  1946.      wanted to override Perl's idea of _g_e_t_h_o_s_t_b_y_n_a_m_e() and _g_e_t_h_o_s_t_b_y_a_d_d_r() so
  1947.      that they would return objects that acted like C structures.  We don't
  1948.      care about high-falutin' OO gunk.  All we want is for these objects to
  1949.      act like structs in the C sense.
  1950.  
  1951.          use Socket;
  1952.          use Net::hostent;
  1953.          $h = gethostbyname("perl.com");  # object return
  1954.          printf "perl.com's real name is %s, address %s\n",
  1955.              $h->name, inet_ntoa($h->addr);
  1956.  
  1957.      Here's how to do this using the Class::Struct module.  The crux is going
  1958.      to be this call:
  1959.  
  1960.          struct 'Net::hostent' => [          # note bracket
  1961.              name       => '$',
  1962.              aliases    => '@',
  1963.              addrtype   => '$',
  1964.              'length'   => '$',
  1965.              addr_list  => '@',
  1966.           ];
  1967.  
  1968.      Which creates object methods of those names and types.  It even creates a
  1969.      _n_e_w() method for us.
  1970.  
  1971.      We could also have implemented our object this way:
  1972.  
  1973.  
  1974.  
  1975.  
  1976.  
  1977.                                                                        PPPPaaaaggggeeee 33330000
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1985.  
  1986.  
  1987.  
  1988.          struct 'Net::hostent' => {          # note brace
  1989.              name       => '$',
  1990.              aliases    => '@',
  1991.              addrtype   => '$',
  1992.              'length'   => '$',
  1993.              addr_list  => '@',
  1994.           };
  1995.  
  1996.      and then Class::Struct would have used an anonymous hash as the object
  1997.      type, instead of an anonymous array.  The array is faster and smaller,
  1998.      but the hash works out better if you eventually want to do inheritance.
  1999.      Since for this struct-like object we aren't planning on inheritance, this
  2000.      time we'll opt for better speed and size over better flexibility.
  2001.  
  2002.      Here's the whole implementation:
  2003.  
  2004.          package Net::hostent;
  2005.          use strict;
  2006.  
  2007.          BEGIN {
  2008.              use Exporter   ();
  2009.              use vars       qw(@EXPORT @EXPORT_OK %EXPORT_TAGS);
  2010.              @EXPORT      = qw(gethostbyname gethostbyaddr gethost);
  2011.              @EXPORT_OK   = qw(
  2012.                                 $h_name         @h_aliases
  2013.                                 $h_addrtype     $h_length
  2014.                                 @h_addr_list    $h_addr
  2015.                             );
  2016.              %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
  2017.          }
  2018.          use vars      @EXPORT_OK;
  2019.  
  2020.          # Class::Struct forbids use of @ISA
  2021.          sub import { goto &Exporter::import }
  2022.  
  2023.          use Class::Struct qw(struct);
  2024.          struct 'Net::hostent' => [
  2025.             name        => '$',
  2026.             aliases     => '@',
  2027.             addrtype    => '$',
  2028.             'length'    => '$',
  2029.             addr_list   => '@',
  2030.          ];
  2031.  
  2032.          sub addr { shift->addr_list->[0] }
  2033.  
  2034.  
  2035.  
  2036.  
  2037.  
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043.                                                                        PPPPaaaaggggeeee 33331111
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2051.  
  2052.  
  2053.  
  2054.          sub populate (@) {
  2055.              return unless @_;
  2056.              my $hob = new();  # Class::Struct made this!
  2057.              $h_name     =    $hob->[0]              = $_[0];
  2058.              @h_aliases  = @{ $hob->[1] } = split ' ', $_[1];
  2059.              $h_addrtype =    $hob->[2]              = $_[2];
  2060.              $h_length   =    $hob->[3]              = $_[3];
  2061.              $h_addr     =                             $_[4];
  2062.              @h_addr_list = @{ $hob->[4] } =         @_[ (4 .. $#_) ];
  2063.              return $hob;
  2064.          }
  2065.  
  2066.          sub gethostbyname ($)  { populate(CORE::gethostbyname(shift)) }
  2067.  
  2068.          sub gethostbyaddr ($;$) {
  2069.              my ($addr, $addrtype);
  2070.              $addr = shift;
  2071.              require Socket unless @_;
  2072.              $addrtype = @_ ? shift : Socket::AF_INET();
  2073.              populate(CORE::gethostbyaddr($addr, $addrtype))
  2074.          }
  2075.  
  2076.          sub gethost($) {
  2077.              if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
  2078.                 require Socket;
  2079.                 &gethostbyaddr(Socket::inet_aton(shift));
  2080.              } else {
  2081.                 &gethostbyname;
  2082.              }
  2083.          }
  2084.  
  2085.          1;
  2086.  
  2087.      We've snuck in quite a fair bit of other concepts besides just dynamic
  2088.      class creation, like overriding core functions, import/export bits,
  2089.      function prototyping, short-cut function call via &whatever, and function
  2090.      replacement with goto &whatever.  These all mostly make sense from the
  2091.      perspective of a traditional module, but as you can see, we can also use
  2092.      them in an object module.
  2093.  
  2094.      You can look at other object-based, struct-like overrides of core
  2095.      functions in the 5.004 release of Perl in File::stat, Net::hostent,
  2096.      Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime,
  2097.      User::grent, and User::pwent.  These modules have a final component
  2098.      that's all lowercase, by convention reserved for compiler pragmas,
  2099.      because they affect the compilation and change a builtin function.  They
  2100.      also have the type names that a C programmer would most expect.
  2101.  
  2102.      DDDDaaaattttaaaa MMMMeeeemmmmbbbbeeeerrrrssss aaaassss VVVVaaaarrrriiiiaaaabbbblllleeeessss
  2103.  
  2104.  
  2105.  
  2106.  
  2107.  
  2108.  
  2109.                                                                        PPPPaaaaggggeeee 33332222
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2117.  
  2118.  
  2119.  
  2120.      If you're used to C++ objects, then you're accustomed to being able to
  2121.      get at an object's data members as simple variables from within a method.
  2122.      The Alias module provides for this, as well as a good bit more, such as
  2123.      the possibility of private methods that the object can call but folks
  2124.      outside the class cannot.
  2125.  
  2126.      Here's an example of creating a Person using the Alias module.  When you
  2127.      update these magical instance variables, you automatically update value
  2128.      fields in the hash.  Convenient, eh?
  2129.  
  2130.          package Person;
  2131.  
  2132.          # this is the same as before...
  2133.          sub new {
  2134.               my $that  = shift;
  2135.               my $class = ref($that) || $that;
  2136.               my $self = {
  2137.                  NAME  => undef,
  2138.                  AGE   => undef,
  2139.                  PEERS => [],
  2140.              };
  2141.              bless($self, $class);
  2142.              return $self;
  2143.          }
  2144.  
  2145.          use Alias qw(attr);
  2146.          use vars qw($NAME $AGE $PEERS);
  2147.  
  2148.          sub name {
  2149.              my $self = attr shift;
  2150.              if (@_) { $NAME = shift; }
  2151.              return    $NAME;
  2152.          }
  2153.  
  2154.          sub age {
  2155.              my $self = attr shift;
  2156.              if (@_) { $AGE = shift; }
  2157.              return    $AGE;
  2158.          }
  2159.  
  2160.          sub peers {
  2161.              my $self = attr shift;
  2162.              if (@_) { @PEERS = @_; }
  2163.              return    @PEERS;
  2164.          }
  2165.  
  2166.          sub exclaim {
  2167.              my $self = attr shift;
  2168.              return sprintf "Hi, I'm %s, age %d, working with %s",
  2169.                  $NAME, $AGE, join(", ", @PEERS);
  2170.          }
  2171.  
  2172.  
  2173.  
  2174.  
  2175.                                                                        PPPPaaaaggggeeee 33333333
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2183.  
  2184.  
  2185.  
  2186.          sub happy_birthday {
  2187.              my $self = attr shift;
  2188.              return ++$AGE;
  2189.          }
  2190.  
  2191.      The need for the use vars declaration is because what Alias does is play
  2192.      with package globals with the same name as the fields.  To use globals
  2193.      while use strict is in effect, you have to predeclare them.  These
  2194.      package variables are localized to the block enclosing the _a_t_t_r() call
  2195.      just as if you'd used a _l_o_c_a_l() on them.  However, that means that
  2196.      they're still considered global variables with temporary values, just as
  2197.      with any other _l_o_c_a_l().
  2198.  
  2199.      It would be nice to combine Alias with something like Class::Struct or
  2200.      Class::MethodMaker.
  2201.  
  2202.      NNNNOOOOTTTTEEEESSSS
  2203.  
  2204.      OOOObbbbjjjjeeeecccctttt TTTTeeeerrrrmmmmiiiinnnnoooollllooooggggyyyy
  2205.  
  2206.      In the various OO literature, it seems that a lot of different words are
  2207.      used to describe only a few different concepts.  If you're not already an
  2208.      object programmer, then you don't need to worry about all these fancy
  2209.      words.  But if you are, then you might like to know how to get at the
  2210.      same concepts in Perl.
  2211.  
  2212.      For example, it's common to call an object an _i_n_s_t_a_n_c_e of a class and to
  2213.      call those objects' methods _i_n_s_t_a_n_c_e _m_e_t_h_o_d_s.  Data fields peculiar to
  2214.      each object are often called _i_n_s_t_a_n_c_e _d_a_t_a or _o_b_j_e_c_t _a_t_t_r_i_b_u_t_e_s, and data
  2215.      fields common to all members of that class are _c_l_a_s_s _d_a_t_a, _c_l_a_s_s
  2216.      _a_t_t_r_i_b_u_t_e_s, or _s_t_a_t_i_c _d_a_t_a _m_e_m_b_e_r_s.
  2217.  
  2218.      Also, _b_a_s_e _c_l_a_s_s, _g_e_n_e_r_i_c _c_l_a_s_s, and _s_u_p_e_r_c_l_a_s_s all describe the same
  2219.      notion, whereas _d_e_r_i_v_e_d _c_l_a_s_s, _s_p_e_c_i_f_i_c _c_l_a_s_s, and _s_u_b_c_l_a_s_s describe the
  2220.      other related one.
  2221.  
  2222.      C++ programmers have _s_t_a_t_i_c _m_e_t_h_o_d_s and _v_i_r_t_u_a_l _m_e_t_h_o_d_s, but Perl only
  2223.      has _c_l_a_s_s _m_e_t_h_o_d_s and _o_b_j_e_c_t _m_e_t_h_o_d_s.  Actually, Perl only has methods.
  2224.      Whether a method gets used as a class or object method is by usage only.
  2225.      You could accidentally call a class method (one expecting a string
  2226.      argument) on an object (one expecting a reference), or vice versa.
  2227.  
  2228.      From the C++ perspective, all methods in Perl are virtual.  This, by the
  2229.      way, is why they are never checked for function prototypes in the
  2230.      argument list as regular builtin and user-defined functions can be.
  2231.  
  2232.      Because a class is itself something of an object, Perl's classes can be
  2233.      taken as describing both a "class as meta-object" (also called _o_b_j_e_c_t
  2234.      _f_a_c_t_o_r_y) philosophy and the "class as type definition" (_d_e_c_l_a_r_i_n_g
  2235.      behaviour, not _d_e_f_i_n_i_n_g mechanism) idea.  C++ supports the latter notion,
  2236.      but not the former.
  2237.  
  2238.  
  2239.  
  2240.  
  2241.                                                                        PPPPaaaaggggeeee 33334444
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2249.  
  2250.  
  2251.  
  2252. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  2253.      The following manpages will doubtless provide more background for this
  2254.      one:  the _p_e_r_l_m_o_d manpage, the _p_e_r_l_r_e_f manpage, the _p_e_r_l_o_b_j manpage, the
  2255.      _p_e_r_l_b_o_t manpage, the _p_e_r_l_t_i_e manpage, and the _o_v_e_r_l_o_a_d manpage.
  2256.  
  2257. AAAAUUUUTTTTHHHHOOOORRRR AAAANNNNDDDD CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  2258.      Copyright (c) 1997, 1998 Tom Christiansen All rights reserved.
  2259.  
  2260.      When included as part of the Standard Version of Perl, or as part of its
  2261.      complete documentation whether printed or otherwise, this work may be
  2262.      distributed only under the terms of Perl's Artistic License.  Any
  2263.      distribution of this file or derivatives thereof _o_u_t_s_i_d_e of that package
  2264.      require that special arrangements be made with copyright holder.
  2265.  
  2266.      Irrespective of its distribution, all code examples in this file are
  2267.      hereby placed into the public domain.  You are permitted and encouraged
  2268.      to use this code in your own programs for fun or for profit as you see
  2269.      fit.  A simple comment in the code giving credit would be courteous but
  2270.      is not required.
  2271.  
  2272. CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  2273.      AAAAcccckkkknnnnoooowwwwlllleeeeddddggggmmmmeeeennnnttttssss
  2274.  
  2275.      Thanks to Larry Wall, Roderick Schertler, Gurusamy Sarathy, Dean
  2276.      Roehrich, Raphael Manfredi, Brent Halsey, Greg Bacon, Brad Appleton, and
  2277.      many others for their helpful comments.
  2278.  
  2279.  
  2280.  
  2281.  
  2282.  
  2283.  
  2284.  
  2285.  
  2286.  
  2287.  
  2288.  
  2289.  
  2290.  
  2291.  
  2292.  
  2293.  
  2294.  
  2295.  
  2296.  
  2297.  
  2298.  
  2299.  
  2300.  
  2301.  
  2302.  
  2303.  
  2304.  
  2305.  
  2306.  
  2307.                                                                        PPPPaaaaggggeeee 33335555
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314. PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))                                                        PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2315.  
  2316.  
  2317.  
  2318.  
  2319.  
  2320.  
  2321.  
  2322.  
  2323.  
  2324.  
  2325.  
  2326.  
  2327.  
  2328.  
  2329.  
  2330.  
  2331.  
  2332.  
  2333.  
  2334.  
  2335.  
  2336.  
  2337.  
  2338.  
  2339.  
  2340.  
  2341.  
  2342.  
  2343.  
  2344.  
  2345.  
  2346.  
  2347.  
  2348.  
  2349.  
  2350.  
  2351.  
  2352.  
  2353.  
  2354.  
  2355.  
  2356.  
  2357.  
  2358.  
  2359.  
  2360.  
  2361.  
  2362.  
  2363.  
  2364.  
  2365.  
  2366.  
  2367.  
  2368.  
  2369.  
  2370.                                                                        PPPPaaaaggggeeee 33336666
  2371.  
  2372.  
  2373.  
  2374.  
  2375.  
  2376.  
  2377.